<template>
    <div>
        <a-row>
            <a-col>
                <a-form-item label="服务类型">
                    <a-radio-group v-model="productType" @change="getProductList" default-value="1">
                        <a-radio :value="1" :disabled="isProductTypeDisabled">保洁</a-radio>
                        <a-radio :value="3" :disabled="isProductTypeDisabled">保养</a-radio>
                        <a-radio :value="2" :disabled="isProductTypeDisabled">搬家</a-radio>
                        <a-radio :value="4" :disabled="isProductTypeDisabled">维修</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="选择服务" validate-trigger="blur" :rules="[{ required: true, message: '请选择服务类型', }]">
                    <a-select placeholder="选择服务" @change="getTree" v-model="service" :options="productTreeList"
                        :field-names="{ value: 'id', label: 'name' }"></a-select>
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="选择收费类型" @change="charge" :rules="[{ required: true, message: '选择收费类型' }]">
                    <a-radio-group v-model="chargeType">
                        <a-radio v-for="item in chargeTypeList" :key="item.value" :value="item.value" :disabled="isChargeTypeDisabled(item.value)">{{ item.label }}</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-col>
        </a-row>

        <!-- 动态表格 -->
        <a-row>
            <a-col>
                <a-button type="primary" @click="addRow">添加一行</a-button>
                <a-table summary-text="总计金额" :columns="table_columns" :data="productList" :summary="summary">
                    <template #name="{ column, record, index }">
                        <a-tree-select v-model="record.productSpecId" :data="record.specTreeData" placeholder="请选择规格"
                            :field-names="{ key: 'id', title: 'name' }" @change="changeTree(record)" />
                    </template>
                    <template #num="{ record }">
                        <a-input-number v-model="record.num" :min="1" placeholder="数量" />
                    </template>
                    <template #price="{ record }">
                        <span v-if="chargeType === 1 || chargeType === 5">{{ record.price }}</span>
                        <span v-else-if="chargeType === 2">
                            {{ record.staffPrice }}
                        </span>
                        <span v-else>
                            0
                        </span>
                    </template>
                    <template #sumPrice="{ record }">
                        <span v-if="chargeType === 1 || chargeType === 5">{{ (record.price * record.num).toFixed(2) }}</span>
                        <span v-else-if="chargeType === 2">
                            {{( record.staffPrice * record.num).toFixed(2) }}
                        </span>
                        <span v-else>
                            0
                        </span>
                    </template>
                    <template #operation="{ rowIndex }">
                        <a-button type="text" @click="deleteRow(rowIndex)">删除</a-button>
                    </template>
                    <template #summary-cell="{ column, record, rowIndex }">
                        <div>{{ record[column.dataIndex] }}</div>
                    </template>
                </a-table>
            </a-col>
        </a-row>
    </div>
</template>
  
<script setup lang="ts">
import { ref, defineProps, defineEmits, computed, watch } from 'vue';
import { getSpecTreeList, getServiceListNoPage, getPrice } from "@/api/service";
import Message from '@arco-design/web-vue/es/message';

const props = defineProps({
    modelValue: Object,
    productType: {
        type: [Number, String],
        default: null // 默认值为null，表示没有外部传递的值
    },
    chargeType: {
        type: [Number, String],
        default: null // 默认值为null，表示没有外部传递的值
    }
});

const emit = defineEmits(['update:modelValue']);

const productType = ref(props.productType);
const service = ref(props.modelValue?.service);
const chargeType = ref(props.chargeType || props.modelValue?.chargeType);

const productList = ref<any>([]);
const specTreeData = ref([]);
const productTreeList = ref([]);

const isProductTypeDisabled = computed(() => props.productType !== null);

const chargeTypeList = computed(() => {
  return [
    { label: "面客订单", value: 1 },
    { label: "内部员工", value: 2 },
    { label: "家装订单", value: 3 },
    { label: "质保内", value: 4 },
    ...(productType.value !== 4 ? [{ label: "质保外", value: 5 }] : [{ label: "内部结算订单", value: 6 }]), // 只在非维修服务下显示“质保外”
  ];
});

const table_columns = [
    { title: "规格名称", dataIndex: "name", hideInSearch: true, slotName: 'name' },
    { title: "数量", dataIndex: "num", hideInSearch: true, slotName: 'num' },
    { title: "单价/元", dataIndex: "price", hideInSearch: true, slotName: 'price' },
    { title: "总价/元", dataIndex: "sumPrice", hideInSearch: true, slotName: 'sumPrice' },
    { title: "操作", dataIndex: "operation", hideInSearch: true, slotName: "operation" },
];

const getProductList = async () => {
    const res  =( await getServiceListNoPage(productType.value)) as any;
    productTreeList.value = res.data;
    service.value = '请选择服务'
    productList.value = []
    updateModelValue();
};

const charge = async () => {
    updateModelValue()
};

const getTree = async () => {
    const specResponse = (await getSpecTreeList(service.value)) as any;
    if (specResponse) {
        specTreeData.value = specResponse.data;
    } else {
        console.error("获取规格树数据失败");
    }
    updateModelValue();
};

const changeTree = async (record) => {
    const key = record.productSpecId;
    const requData = { id: key };
    const price = await getPrice(requData);
    record.price = price.data.discountPrice;
    record.staffPrice = price.data.staffPrice;
    updateModelValue();
};

const addRow = () => {
    if(specTreeData.value.length === 0){
        Message.warning('服务下规格为空');
        return
    }
    productList.value.push({
        productId: service.value,
        productSpecId: null,
        num: 1,
        price: 0,
        specTreeData:specTreeData.value
    });
    updateModelValue();
};

const deleteRow = (index: number) => {
    productList.value.splice(index, 1);
    updateModelValue();
};

const summary = ({ columns, data }) => {
    let countData = {
        sumPrice: 0,
    };

    data.forEach(record => {
        if (chargeType.value === 1 || chargeType.value === 5) {
            countData.sumPrice += record.price * record.num;
        } else if (chargeType.value === 2) {
            countData.sumPrice += record.staffPrice * record.num;
        } else {
            countData.sumPrice += 0;
        }
    });

    return [{
        name: '总价',
        sumPrice: countData.sumPrice.toFixed(2),
    }];
};

const updateModelValue = () => {
    emit('update:modelValue', {
        productType: productType.value,
        service: service.value,
        chargeType: chargeType.value,
        productList: productList.value,
    });
    console.log(chargeType.value, 'chargeType.value')
};

const isChargeTypeDisabled = (value) => {
    if (props.chargeType !== null) {
        return props.chargeType !== value;
    }
    return false;
};

// 监听 props.productType 的变化
watch(() => props.productType, (newVal) => {
    productType.value = newVal;
    if (newVal !== null) {
        getProductList();
        getTree();
    }
});

// 监听 props.chargeType 的变化
watch(() => props.chargeType, (newVal) => {
    chargeType.value = newVal;
    updateModelValue();
});

// 初始化时获取产品列表
if (props.productType === null) {
    getProductList();
} else {
    getProductList();
    getTree();
}
</script>